package com.why.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.why.dao.mybatis.IndexDao;
import com.why.dao.mybatis.OrgDao;
import com.why.entity.Cell;
import com.why.entity.EUDataGrid;
import com.why.entity.EasyUiTree;
import com.why.entity.Index;
import com.why.entity.IndexData;
import com.why.entity.Org;
import com.why.util.ExcelUtil;

@Service
public class IndexService {

	@Resource
	private IndexDao indexDao;
	@Resource
	private OrgDao orgDao;

	private String defalut_id="1";
	
	public EasyUiTree getAllIndex() {
		// TODO Auto-generated method stub
		List<Index> persons = indexDao.getaAll();
		
		Index root = new Index();;
		for(Index i:persons){
			String up_index = i.getUp_id();
			if(up_index != null){//根据父节点Id将该节点添加到其父节点下
				for(Index in:persons){
					if(in.getId().equals(up_index)){
						in.setChildren(i);
						break;
					}
				}
			}else{//父节点为空则为根节点
				root = i;
			}
		}
//		return temp_map.get("0");
		return this.transition(root);
	}
	
	private EasyUiTree transition(Index index){
		String up_index = index.getUp_id();
		String path = index.getPath();
		EasyUiTree eut = new EasyUiTree(index.getId(),index.getIndex_name());
		eut.setAttribuate(path);
		eut.setAttributes(path);
		eut.setUpid(up_index);
		eut.setPath(path);
		if(index.hasChildren()){
			List<Index> children = index.getChildren();
			for(Index child:children){
				eut.addChild(transition(child));
			}
		}
		return eut;
	}
	

	public EUDataGrid getIndexByCode(String index_code) {
		// TODO Auto-generated method stub
		List<Index> indexs = indexDao.getIndexByCode(index_code);
		EUDataGrid dg = new EUDataGrid();
		dg.setTotal(indexs.size());
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		for(Index i:indexs){
			Map<String,String> info = new HashMap<String,String>();
			info.put("id", i.getId());
			info.put("index_name", i.getIndex_name());
			info.put("unit", i.getUnit());
			info.put("index_order", i.getIndex_order());
			info.put("remark", i.getRemark());
			list.add(info);
		}
		dg.setRows(list);
		return dg;
	}
	
	
	public String getSubIndex(){
		return this.getSubIndex(defalut_id);
	}
	
	private String getIndexPath(String id){
		return indexDao.getIndexPathById(id);
	}
	
	public String getSubIndex(String id){
		String cloumns = null;
		String path = this.getIndexPath(id);
		List<Index> lists = indexDao.getSubIndexs(path);
		for(Index index : lists){
			String up_id = index.getUp_id();
			if(up_id != null){
				for(Index sub : lists){
					if(up_id.equals(sub.getId())){
						sub.setChildren(index);
						break;
					}
				}
			}
		}
		Index root = null;
		for(Index index:lists){
			if(id.equals(index.getId())){
//				cloumns = this.creatCloumns(index);
				root = index;
				break;
			}
		}
		List<Index> r = new ArrayList<Index>();
		r.add(root);
		cloumns = creatCloumns(r);
		cloumns=cloumns.substring(1, cloumns.length()-1);
		
		cloumns = "[[{field:'area',align:'center',title:'地市',width:100,rowspan:3},{field:'id',align:'center',title:'编码',hidden:true,width:100,rowspan:3},"+cloumns+"]";
//		System.out.println(cloumns);
		return cloumns;
	}
	
	private String creatCloumns(List<Index> list){
		int width = 0;
		StringBuffer columns = new StringBuffer("["); 
		List<Index> children = new ArrayList<Index>();
		for(Index child : list){
			if(child.hasChildren()){
//				int num = child.getChildrenNum();
				columns.append("{title:'").append(child.getIndex_name()).append("',colspan:").append(child.getChildrenNum()).append("},");
				children.addAll(child.getChildren());
			}else{
				width = child.getIndex_name().length()*20;
				columns.append("{field:'").append(child.getId()).append("',title:'");
				columns.append(child.getIndex_name()).append("',align:'center',width:");
				columns.append(width).append(",editor:{type:'numberbox',options:{precision:1}}},");
			}
		}
		String str = columns.toString();
		str = str.substring(0, str.length()-1)+"],";
		if(children.size()>0){
			str = str + creatCloumns(children);
		}
		return str;
	}
	
//	private String creatCloumns(Index index){
//		int width = 0;
//		StringBuffer columns = new StringBuffer(); 
//		if(index.hasChildren()){
//			List<Index> children = index.getChildren();
//			for(Index child : children){
//				if(child.hasChildren()){
//					columns.append("{title:'").append(child.getIndex_name()).append("',colspan:").append(child.getChildrenNum()).append("}");
//				}else{
//					columns.append(creatCloumns(child));
//				}
//			}
//		}else{
//			width = index.getIndex_name().length()*20;
//			columns.append("{field:'").append(index.getId()).append("',title:'");
//			columns.append(index.getIndex_name()).append("',align:'center',width:");
//			columns.append(width).append(",editor='numberbox'},");
//		}
//		return columns.toString();
//	}
//	
//	private String creatCloumn(Index index){
//		StringBuffer columns = new StringBuffer(); 
//		int width = index.getIndex_name().length()*20;
//		columns.append("{field:'").append(index.getId()).append("',title:'");
//		columns.append(index.getIndex_name()).append("',align:'center',width:");
//		columns.append(width).append("},");
//		return columns.toString();
//	}
//	
//	private String creatCloumn(Index index,boolean area,boolean date){
//		int width = 0;
//		StringBuffer columns = new StringBuffer(); 
//		if(index.hasChildren()){
//			for(Index child : index.getChildren()){
//				columns.append(creatCloumn(child,false,false));
//			}
//		}else{
//			width = index.getIndex_name().length()*20;
//			columns.append("{field:'").append(index.getId()).append("',title:'");
//			columns.append(index.getIndex_name()).append("',align:'center',width:");
//			columns.append(width).append("},");
//		}
////		columns.append("]]");
//		return columns.toString();
//	}
	
	public void importToTable(String filepath){
		List<IndexData> list = ExcelUtil.getIndexDataObj(filepath);
		List<IndexData> insert_list = new ArrayList<IndexData>();
		List<IndexData> update_list = new ArrayList<IndexData>();
		for(IndexData d : list){
			String year = d.getYear();
			String org_id = d.getOrg_id();
			String index_id = d.getIndex_id();
			IndexData index_data = indexDao.getIndexData(year, org_id, index_id);
			if(index_data ==  null){
				insert_list.add(d);
			}else{
				if(!(index_data.getData_value()).equals(d.getData_value()) || 
						!(index_data.getData_source()).equals(d.getData_source())){
					index_data.setData_value(d.getData_value());
					index_data.setData_source(d.getData_source());
					update_list.add(index_data);
				}
			}
		}
		indexDao.insertIndexDataBatch(insert_list);
		indexDao.updateIndexDataBatch(update_list);
		System.out.println("finish");
	}
	
	public Workbook exportToExcel(String index_id,String org_id,String start){
		try {
			Map<String,Object> info = this.getFileHeader(index_id, true);
			List<List<Cell>> header = (List<List<Cell>>) info.get("data"); 
			List<String> title = (List<String>) info.get("title");
			//获取内容
//			OrgService os = new OrgService();
			List<List<Object>> list = this.getExport_data(org_id, start, title);
			Workbook wb = ExcelUtil.exportExcel(header,list,start);
			return wb;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	private Map<String,Object> getFileHeader(String index_id,boolean flag) throws Exception{
		String path = this.getIndexPath(index_id);
		List<Index> lists = indexDao.getSubIndexs(path);
		Index root = this.getRoot(index_id, lists);
		int level = this.getIndexLevel(root.getChildren(),1);
		List<Index> temp = new ArrayList<Index>();
		List<List<Cell>> pro = new ArrayList<List<Cell>>();
		temp.add(root);
		List<String> title = new ArrayList<String>();
		for(int i=0;i<level;i++){
			List<Index> leve_temp = new ArrayList<Index>();
			List<Cell> cs = new ArrayList<Cell>();
			if(i==0){
				if(flag){
					cs.add(new Cell("area","地市",1,level,null));
					title.add("area");
				}else{
					cs.add(new Cell("year","年份",1,level,null));
					title.add("year");
				}
			}
			for(Index t:temp){
//				int i_l = this.getIndexLevel(t, 0);
//				System.out.println("levle:"+i_l);
				int rowspan = 1;
				int colspan=1;
				if(t.hasChildren()){
					colspan = t.getChildrenNum();
					leve_temp.addAll(t.getChildren());
				}else{
					title.add(t.getId());
					if(i==0)
						rowspan = level;
				}
				cs.add(new Cell(t.getId(),t.getIndex_name(),colspan,rowspan,null));
			}
			temp = leve_temp;
			pro.add(cs);
		}
		Map<String,Object> info = new HashMap<String,Object>();
		info.put("data", pro);
		info.put("title", title);
		return info;
//		ExcelUtil.exportExcel(pro);
	}
	
	
	private Index getRoot(String index_id,List<Index> lists){
		Map<String,Index> map = new HashMap<String,Index>();
		for(Index index : lists){
			map.put(index.getId(), index);
		}
		for(Index index : lists){
			Index f_index = map.get(index.getUp_id());
			if(null != f_index){
				f_index.setChildren(map.get(index.getId()));
			}
		}
		return map.get(index_id);
	}
	
	private int getIndexLevel(Index indexs,int num){
		List<Index> temp = new ArrayList<Index>();
		temp.add(indexs);
		return this.getIndexLevel(temp, num);
	}
	
	private int getIndexLevel(List<Index> indexs,int num){
		if(null==indexs || indexs.size()==0)
			return num;
		List<Index> lists = new ArrayList<Index>();
		for(Index i : indexs){
			if(i.hasChildren()){
				lists.addAll(i.getChildren());
			}
		}
		if(lists.size()>0){
			return getIndexLevel(lists,++num);
		}
		return ++num;
	}
	
	private String getPath(String org_id){
		return orgDao.getOrgPathById(org_id);
	}
	
	public List<List<Object>> getExport_data(String org_id, String start,List<String> title) {
		List<List<Object>> list = new ArrayList<List<Object>>();
		String path = getPath(org_id);
		List<Org> orgs = orgDao.getOrgsByPath(path);
		if(orgs.size()>0){
			for(Org org:orgs){
				List<Object> o_list = new ArrayList<Object>();
				o_list.add(org);
				List<IndexData> index_datas = orgDao.getIndexData(org.getId(),start);
				Map<String,IndexData> d_map = new HashMap<String,IndexData>();
				for(IndexData index:index_datas){
					d_map.put(index.getIndex_id(), index);
				}
				for(String t:title){
					if(t.equals("area")){
						continue;
					}
					IndexData temp = d_map.get(t);
					if(temp == null){
						IndexData t_o = new IndexData();
						t_o.setIndex_id(t);
						o_list.add(t_o);
					}else{
						o_list.add(temp);
					}
				}
				list.add(o_list);
			}
		}
		return list;
	}
	
	
	public IndexData getIndexDataInfo(String index_id,String year,String org_id){
		IndexData indexdate = indexDao.getIndexData(year, org_id, index_id);
		return indexdate;
	}

	public String editIndexData(IndexData indexdate) {
		// TODO Auto-generated method stub
		String id = indexdate.getId();
		if(null == id || "".equals(id)){
			indexDao.insertIndexData(indexdate);
		}else{
			indexDao.updateIndexData(indexdate);
		}
		return "succeful";
	}

	public String editIndexInfo(Index index) {
		// TODO Auto-generated method stub
		String id = index.getId();
		if(null == id || "".equals(id)){
			index.setPath(index.getPath()+"/"+index.getIndex_name());
			indexDao.insertIndexInfo(index);
		}else{
			indexDao.updateIndexInfo(index);
		}
		return "succeful";
	}
	
	public String deleteIndexInfo(String id) {
		// TODO Auto-generated method stub
		indexDao.deleteIndexInfo(id);
		return "succeful";
	}
	
	
}
